const app = getApp();
const { request } = require('../../../utils/request');

Page({
    data: {
        name: '',
        phone: '',
        address: '',
        isDefault: false // 初始化 isDefault 为 false
    },

    onNameInput(e) {
        this.setData({ name: e.detail.value });
    },

    onPhoneInput(e) {
        this.setData({ phone: e.detail.value });
    },

    onAddressInput(e) {
        this.setData({ address: e.detail.value });
    },

    // 切换默认地址状态
    toggleDefault() {
        this.setData({ isDefault: !this.data.isDefault });
    },

    async submitAddress() {
        const newAddress = {
            contact_name: this.data.name,
            contact_phone: this.data.phone,
            full_address: this.data.address,
            // 确保正确引用 isDefault 的值
            is_default: this.data.isDefault 
        };

        console.log('新增地址数据:', newAddress); // 打印数据，方便调试

        try {
            const res = await request({
                url: '/address',
                method: 'POST',
                data: newAddress,
                showLoading: true
            });

            console.log('新增地址接口响应:', res); // 打印接口响应

            if (res.code === 2000) {
                wx.navigateBack();
                wx.showToast({
                    title: '新增成功',
                    icon: 'success'
                });
            } else {
                wx.showToast({
                    title: `新增失败: ${res.message || '未知错误'}`,
                    icon: 'none'
                });
                console.error('新增地址失败:', res.message);
            }
        } catch (error) {
            wx.showToast({
                title: `请求出错: ${error.message || '未知错误'}`,
                icon: 'none'
            });
            console.error('新增地址请求出错:', error);
        }
    }
});
